package com.lizhenhua.orderitemadd.service.impl;

import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.lizhenhua.fmmall.entity.OrderItem;
import com.lizhenhua.fmmall.entity.ShoppingCartVo;
import com.lizhenhua.orderitemadd.mapper.OrderItemMapper;
import com.lizhenhua.orderitemadd.service.OrderItemAddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class OrderItemAddServiceImpl implements OrderItemAddService {
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    @Transactional    // 和下面Lcn 一起用
    @LcnTransaction  // lcn模式 分布式事务注解
    public int saveOrder(List<ShoppingCartVo> list, String orderId) {
        int j = 1;
        for (ShoppingCartVo s : list
        ) {
            //new Random().nextInt(89999)+10000) 降低重复概率
            Integer cnum = Integer.parseInt(s.getCartNum()); // 商品数量
            Integer sPrice = Integer.parseInt(s.getSellPrice()); // 商品的售价
            String itemId = System.currentTimeMillis() + "+" + (new Random().nextInt(89999) + 10000);
            OrderItem orderItem = new OrderItem(
                    itemId, orderId, s.getProductId(), s.getProductName(),
                    s.getProductImg(), s.getSkuId(), s.getSkuName(), new BigDecimal(sPrice),
                    cnum, new BigDecimal(sPrice * cnum), new Date(), new Date(), 0);
            int insert1 = orderItemMapper.insert(orderItem); // 一个一个保存  当我构造一个商品快照我就保存一个

            // 只要有一个insert1 为零 j就为0
            j *= insert1;
        }
        return j;

    }
}
